﻿using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Ledict.ConditionExtract.Frm.NodeTree
{
    public partial class ArgumentConfig : BaseForm
    {
        public ConvertMode cm { get; set; }
        public ConvertMode cmUpdate { get; set; }
        ConvertModeBLL convertModeBll = new ConvertModeBLL();
        ExtractFeatureBLL efBll = new ExtractFeatureBLL();
        NewIDBLL newid = new NewIDBLL();
        public bool IsAdd { get; set; }
        public string state = string.Empty;
        public string efId = string.Empty;

        //字典值类型
        private int dictionaryType;
        public bool isAYDataAdd;
        CaseCauseBLL caseCauseBll = new CaseCauseBLL();
        ArgumentRelBLL argumentRelBll = new ArgumentRelBLL();
        public ArgumentRelModel arm { get; set; }

        //案由数据表
        private static DataTable sysCaseCauseTable = new DataTable();
        /// <summary>
        /// 案件ID
        /// </summary>
        public string DocType { get; set; }

        public ArgumentConfig(int dicType, bool xgXZ = false)
        {
            InitializeComponent();
            dictionaryType = dicType;
            if (dicType == 0)
            {
                panelAY.Visible = false;
                txbConvertCode.ReadOnly = txbConvertName.ReadOnly = false;
            }
            else if (dicType == 1)
            {
                //案由字典显示案由选择框
                panelAY.Visible = true;
                LoadSysCaseCauseData();
            }
            isAYDataAdd = xgXZ;
        }

        /// <summary>
        /// 加载案由数据
        /// </summary>
        private void LoadSysCaseCauseData()
        {
            sysCaseCauseTable = caseCauseBll.GetSysCaseCauseData();
            if (sysCaseCauseTable.Rows.Count > 0)
            {
                if (sysCaseCauseTable.Select("ID in('1000','1477','2329','2415','2449') ").Length > 0)
                {
                    DataTable sysCaseCausedt = sysCaseCauseTable.Select(" ID in('1000','1477','2329','2415','2449') ").CopyToDataTable<DataRow>();
                    foreach (DataRow dr in sysCaseCausedt.Rows)
                    {
                        TreeNode node = new TreeNode() { Text = dr["Name"].ToString(), Tag = dr["ID"].ToString() };
                        node.Nodes.Add(new TreeNode());
                        cbTreeViewSysCaseCause.TreeView.Nodes.Add(node);
                    }
                    cbTreeViewSysCaseCause.DropDownStyle = ComboBoxStyle.DropDown;
                    cbTreeViewSysCaseCause.TreeView.AfterExpand += TreeView_AfterExpandCaseCause;
                }
            }
        }

        /// <summary>
        /// 案由数据展开节点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeView_AfterExpandCaseCause(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            DataTable dt = new DataTable();
            if (sysCaseCauseTable.Select(" ParentID='" + e.Node.Tag.ToString() + "' ").Length > 0)
            {
                dt = sysCaseCauseTable.Select(" ParentID='" + e.Node.Tag.ToString() + "' ").CopyToDataTable<DataRow>();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        TreeNode node = new TreeNode { Text = dr["Name"].ToString(), Tag = dr["ID"].ToString() };
                        if (sysCaseCauseTable.Select(" ParentID='" + node.Tag.ToString() + "' ").Length > 0)
                        {
                            DataTable dtt = sysCaseCauseTable.Select(" ParentID='" + node.Tag.ToString() + "' ").CopyToDataTable<DataRow>();
                            if (dtt != null && dtt.Rows.Count > 0)
                            {
                                node.Nodes.Add(new TreeNode());
                            }
                        }
                        e.Node.Nodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 取消按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCanel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;
        }

        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txbConvertCode.Text))
            {
                MessageBox.Show("数据转换方式编号不能为空！");
                txbConvertCode.Focus();
                return;
            }
            if (string.IsNullOrEmpty(txbConvertName.Text))
            {
                MessageBox.Show("中文名称不能为空！");
                txbConvertName.Focus();
                return;
            }
            if (string.IsNullOrEmpty(cbtAtCode.Text))
            {
                MessageBox.Show("字典编号不能为空！");
                cbtAtCode.Focus();
                return;
            }
            if (dictionaryType == 1)
            {
                if (string.IsNullOrEmpty(cbTreeViewSysCaseCause.Text))
                {
                    MessageBox.Show("案由不能为空！");
                    cbTreeViewSysCaseCause.Focus();
                    return;
                }
                if (cm != null && !string.IsNullOrEmpty(cm.CM_ID))
                {
                    DataTable dt = argumentRelBll.GetArgumentRelData(cm.CM_ID);
                    if (dt != null && dt.Rows.Count > 0 && dt.Select(" AR_CauseCode='" + sysCaseCauseTable.Select(" Name='" + cbTreeViewSysCaseCause.Text.Trim() + "'")[0]["ID"].ToString() + "' ").Length > 0 && state == "新增")
                    {
                        MessageBox.Show("该字典值已配置过此案由，请切换后再试！");
                        cbTreeViewSysCaseCause.Focus();
                        return;
                    }
                }
            }
            if (cm == null)
            {
                cm = new ConvertMode();
            }
            if (arm == null)
            {
                arm = new ArgumentRelModel();
            }
            cm.CM_Code = txbConvertCode.Text.Trim();
            cm.CM_CodeCH = txbConvertName.Text.Trim();
            if (dictionaryType == 1)
            {
                cm.CM_CMode = 3;
            }
            else
            {
                cm.CM_CMode = 0;
            }
            if (cbtAtCode.Text.Contains('-'))
            {
                DataRow dr = ElementsConfig.sysArgumentTypeData.Select("AT_Code='" + cbtAtCode.Text.Split('-')[1] + "' and AT_RelatCaseType='" + cbtAtCode.Text.Split('-')[2] + "' ").CopyToDataTable<DataRow>().Rows[0];
                cm.AT_ID = dr["AT_ID"].ToString();
                cm.AT_Code = dr["AT_Code"].ToString();
                cm.AT_WordsMode = dr["AT_WordsMode"].ToString();
            }
            cm.CM_UpdateTime = DateTime.Now;
            cm.AT_Name = cbtAtCode.Text.Split('-')[0].ToString();
            cm.CM_CaseType = DocType;

            ArgumentRelModel argumentModel = new ArgumentRelModel();
            if (arm != null && !string.IsNullOrEmpty(arm.AR_ID))
            {
                argumentModel.AT_ID = cm.AT_ID;
                argumentModel.AT_Code = cm.AT_Code;
                argumentModel.CM_ID = cm.CM_ID;
                argumentModel.AR_ID = arm.AR_ID;
            }
            else
            {
                argumentModel.AR_ID = Snowflake.GetId().ToString();
                argumentModel.CM_ID = cm.CM_ID;
                argumentModel.AT_ID = cm.AT_ID;
                argumentModel.AT_Code = cm.AT_Code;
                argumentModel.CM_ID = cm.CM_ID;
            }
            if (dictionaryType == 1)
            {
                argumentModel.AR_CauseCode = cbTreeViewSysCaseCause.TreeView.SelectedNode == null ? sysCaseCauseTable.Select(" Name='" + cbTreeViewSysCaseCause.Text.Trim() + "'")[0]["ID"].ToString() : cbTreeViewSysCaseCause.TreeView.SelectedNode.Tag.ToString();
            }
            argumentModel.AR_CaseType = DocType;
            //当当前数据是默认数据并且为新增操作时，判断修改数据与默认数据是否一致，不一致就进行重新生成数据进行添加
            if (state == "修改" && (cmUpdate.CM_Code != cm.CM_Code || cmUpdate.CM_CodeCH != cm.CM_CodeCH || cmUpdate.AT_ID != cm.AT_ID || cmUpdate.AT_Code != cm.AT_Code || arm.AR_CauseCode != argumentModel.AR_CauseCode) && cm.CM_Custom == 0)
            {
                cm.CM_ID = Snowflake.GetId().ToString();
                cm.CM_Custom = 1;
                argumentModel.AR_ID = Snowflake.GetId().ToString();
                argumentModel.CM_ID = cm.CM_ID;
                convertModeBll.ConvertModeAdd(cm);
                argumentRelBll.ArgumentRelAdd(argumentModel);

                MessageBox.Show("添加成功！");
            }
            else
            if (!string.IsNullOrEmpty(cm.CM_ID) && state == "修改")
            {
                if (convertModeBll.ConvertModeUpdate(cm) && argumentRelBll.ArgumentRelUpdate(argumentModel))
                {
                    MessageBox.Show("修改成功！");
                }
                else
                {
                    MessageBox.Show("修改失败！");
                }
            }
            else if (!IsAdd && !string.IsNullOrEmpty(cm.CM_ID) && state == "新增")
            {
                if (dictionaryType == 1 && isAYDataAdd)
                {
                    if (argumentRelBll.ArgumentRelAdd(argumentModel))
                    {
                        MessageBox.Show("添加成功！");
                    }
                    else
                    {
                        MessageBox.Show("添加失败！");
                    }
                }
                else
                {
                    cm.CM_Custom = 1;
                    if (convertModeBll.ConvertModeAdd(cm) && argumentRelBll.ArgumentRelAdd(argumentModel))
                    {
                        MessageBox.Show("添加成功！");
                    }
                    else
                    {
                        MessageBox.Show("添加失败！");
                    }
                }
            }
            else if (!IsAdd && string.IsNullOrEmpty(cm.CM_ID) && state == "新增" && !string.IsNullOrEmpty(efId))
            {
                cm.CM_ID = Snowflake.GetId().ToString(); ;
                ExtractFeature ef = new ExtractFeature() { EF_ID = efId, CM_ID = cm.CM_ID };
                argumentModel.CM_ID = cm.CM_ID;
                cm.CM_Custom = 1;
                if (convertModeBll.ConvertModeAdd(cm) && efBll.ExtractFeatureUpdateCMID(ef) && argumentRelBll.ArgumentRelAdd(argumentModel))
                {
                    MessageBox.Show("添加成功！");
                }
                else
                {
                    MessageBox.Show("添加失败！");
                }
            }
            else if (string.IsNullOrEmpty(cm.CM_ID) && IsAdd)
            {
                cm.CM_ID = Snowflake.GetId().ToString();
                argumentModel.CM_ID = cm.CM_ID;
                cm.CM_Custom = 1;
                if (convertModeBll.ConvertModeAdd(cm) && argumentRelBll.ArgumentRelAdd(argumentModel))
                {
                    MessageBox.Show("添加成功！");
                }
                else
                {
                    MessageBox.Show("添加失败！");
                }
            }
            DialogResult = DialogResult.Yes;
            this.Close();
        }

        /// <summary>
        /// 加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ArgumentConfig_Load(object sender, EventArgs e)
        {
            if (cm != null && !string.IsNullOrEmpty(cm.CM_ID))
            {
                txbConvertCode.Text = cm.CM_Code;
                txbConvertName.Text = cm.CM_CodeCH;
                cbtAtCode.Text = cm.AT_Code;
            }
            LoadSysCaseTypeConfig();
            if (arm != null && !string.IsNullOrEmpty(arm.AR_ID))
            {
                cbtAtCode.Text = arm.AT_Code;
                if (!string.IsNullOrEmpty(arm.AR_CauseCode))
                {
                    cbTreeViewSysCaseCause.Text = arm.AR_CauseCode;
                }
                //cbTreeViewSysCaseCause.TreeView.SelectedNode.Tag=arm.AR_CauseCode;
            }
            cmUpdate = new ConvertMode();
            cmUpdate.CM_Code = cm.CM_Code;
            cmUpdate.CM_CodeCH = cm.CM_CodeCH;
            cmUpdate.AT_ID = cm.AT_ID;
            cmUpdate.AT_Code = cm.AT_Code;
            if (isAYDataAdd && state == "新增")
            {
                isAYDataAdd = true;
                txbConvertCode.ReadOnly = txbConvertName.ReadOnly = true;
            }
        }

        /// <summary>
        /// 快速检索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbtAtCode_TextUpdate(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cbtAtCode.Text))
            {
                if (ElementsConfig.sysArgumentTypeData.Select(" AT_Name like '%" + cbtAtCode.Text + "%' or AT_Code like '%" + cbtAtCode.Text + "%' ").Length > 0)
                {
                    DataTable dt1 = ElementsConfig.sysArgumentTypeData.Select(" AT_Name like '%" + cbtAtCode.Text + "%' or AT_Code like '%" + cbtAtCode.Text + "%' ").CopyToDataTable<DataRow>();
                    cbtAtCode.TreeView.Nodes.Clear();
                    if (dt1 != null && dt1.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt1.Rows)
                        {
                            TreeNode node = new TreeNode() { Text = dr["AT_Name"].ToString() + "-" + dr["AT_Code"].ToString() + "-" + (dr["AT_RelatCaseType"] == null ? "" : dr["AT_RelatCaseType"].ToString()), Tag = dr["AT_ID"].ToString() };
                            cbtAtCode.TreeView.Nodes.Add(node);
                        }
                    }
                }
                else
                {
                    cbtAtCode.TreeView.Nodes.Clear();
                }
            }
            else
            {
                cbtAtCode.TreeView.Nodes.Clear();
                if (ElementsConfig.sysArgumentTypeData != null && ElementsConfig.sysArgumentTypeData.Rows.Count > 0)
                {
                    foreach (DataRow dr in ElementsConfig.sysArgumentTypeData.Rows)
                    {
                        TreeNode node = new TreeNode() { Text = dr["AT_Name"].ToString() + "-" + dr["AT_Code"].ToString() + "-" + (dr["AT_RelatCaseType"] == null ? "" : dr["AT_RelatCaseType"].ToString()), Tag = dr["AT_ID"].ToString() };
                        cbtAtCode.TreeView.Nodes.Add(node);
                    }
                }
            }
        }

        DataTable sysCaseTypeTable = new DataTable();
        private void LoadSysCaseTypeConfig()
        {
            SYS_CaseTypeBLL sysCaseTypeBll = new SYS_CaseTypeBLL();
            sysCaseTypeTable = sysCaseTypeBll.GetCaseTypeData();
            if (sysCaseTypeTable.Rows.Count > 0)
            {
                if (sysCaseTypeTable.Select("ParentID is null  or ParentID='' ").Length > 0)
                {
                    DataTable sysCaseTypedt = sysCaseTypeTable.Select("ParentID is null or ParentID='' ").CopyToDataTable<DataRow>();
                    TreeNode commonNode = new TreeNode() { Text = "common", Tag = "common" };
                    cbTreeViewCaseTypeConfig.TreeView.Nodes.Add(commonNode);
                    foreach (DataRow dr in sysCaseTypedt.Rows)
                    {
                        TreeNode node = new TreeNode() { Text = dr["Name"].ToString(), Tag = dr["ID"].ToString() };
                        if (sysCaseTypeTable.Select("  ParentID='" + node.Tag.ToString() + "' ").Length > 0)
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        cbTreeViewCaseTypeConfig.TreeView.Nodes.Add(node);
                    }
                    cbTreeViewCaseTypeConfig.DropDownStyle = ComboBoxStyle.DropDown;
                    cbTreeViewCaseTypeConfig.TreeView.AfterExpand += TreeView_AfterExpandCaseType;
                    cbTreeViewCaseTypeConfig.TreeView.AfterCheck += TreeView_AfterCheck;
                }
            }
        }

        /// <summary>
        /// 案件类型展开节点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeView_AfterExpandCaseType(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            DataTable dt = new DataTable();
            if (sysCaseTypeTable.Select(" ParentID='" + e.Node.Tag.ToString() + "' ").Length > 0)
            {
                dt = sysCaseTypeTable.Select(" ParentID='" + e.Node.Tag.ToString() + "' ").CopyToDataTable<DataRow>();
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        TreeNode node = new TreeNode { Text = dr["Name"].ToString(), Tag = dr["ID"].ToString() };
                        if (sysCaseTypeTable.Select(" ParentID='" + node.Tag.ToString() + "' ").Length > 0)
                        {
                            DataTable dtt = sysCaseTypeTable.Select(" ParentID='" + node.Tag.ToString() + "' ").CopyToDataTable<DataRow>();
                            if (dtt != null && dtt.Rows.Count > 0)
                            {
                                node.Nodes.Add(new TreeNode());
                            }
                        }
                        e.Node.Nodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 案件类型数据选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TreeView_AfterCheck(object sender, TreeViewEventArgs e)
        {
            LoadCaseDocType();
        }

        private void LoadCaseDocType()
        {
            cbtAtCode.TreeView.Nodes.Clear();
            cbtAtCode.Text = "";
            //common的时候直接取字典值 其他类型关联案件类型进行获取字典编号
            if (!string.IsNullOrEmpty(cbTreeViewCaseTypeConfig.Text) && (cbTreeViewCaseTypeConfig.TreeView.SelectedNode.Tag.ToString() == "common" || sysCaseTypeTable.Select(" ID='" + cbTreeViewCaseTypeConfig.TreeView.SelectedNode.Tag.ToString() + "' ").Length > 0))
            {
                string caseType = cbTreeViewCaseTypeConfig.TreeView.SelectedNode.Tag.ToString();
                if (caseType != "common")
                {
                    caseType = sysCaseTypeTable.Select(" ID='" + caseType + "' ")[0]["Code"].ToString();
                }
                if (ElementsConfig.sysArgumentTypeData.Select(" AT_RelatCaseType='" + caseType + "' ").Length > 0)
                {
                    DataTable dt = ElementsConfig.sysArgumentTypeData.Select(" AT_RelatCaseType='" + caseType + "' ").CopyToDataTable();
                    cbtAtCode.TreeView.Nodes.Clear();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            TreeNode node = new TreeNode() { Text = dr["AT_Name"].ToString() + "-" + dr["AT_Code"].ToString() + "-" + (dr["AT_RelatCaseType"] == null ? "" : dr["AT_RelatCaseType"].ToString()), Tag = dr["AT_ID"].ToString() };
                            cbtAtCode.TreeView.Nodes.Add(node);
                        }
                    }
                    cbtAtCode.DropDownStyle = ComboBoxStyle.DropDown;
                }
            }

        }

        /// <summary>
        /// 案由数据文本改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbTreeViewSysCaseCause_TextUpdate(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cbTreeViewSysCaseCause.Text))
            {
                if (sysCaseCauseTable.Select("Name like '%" + cbTreeViewSysCaseCause.Text + "%'").Length > 0)
                {
                    DataTable dt3 = sysCaseCauseTable.Select("Name like '%" + cbTreeViewSysCaseCause.Text + "%'").CopyToDataTable<DataRow>();
                    cbTreeViewSysCaseCause.TreeView.Nodes.Clear();
                    if (dt3 != null && dt3.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt3.Rows.Count; i++)
                        {
                            TreeNode node = new TreeNode();
                            node.Text = dt3.Rows[i]["Name"].ToString();
                            node.Tag = dt3.Rows[i]["ID"].ToString();
                            //if (sysCourtTable.Select("ParentID='" + node.Tag + "'").Length > 0)
                            //{
                            // node.Nodes.Add(new TreeNode());
                            // }
                            cbTreeViewSysCaseCause.TreeView.Nodes.Add(node);
                        }
                    }
                }
                else
                {
                    cbTreeViewSysCaseCause.TreeView.Nodes.Clear();
                }
            }
            else
            {
                cbTreeViewSysCaseCause.TreeView.Nodes.Clear();
                LoadSysCaseCauseData();
            }
        }
    }
}
